from __future__ import absolute_import

import argparse
import logging
import os
import sys
from .. import io
from .. import bash  # for write_script

LOG = logging.getLogger()

def run(p_id_num, las_paths_fn, merge_script_fn, las_merged_fn_fn,
        las_merged_symlink_fn, job_done_fn, p_id_fn):
    with open(p_id_fn, 'w') as stream:
        stream.write(p_id_num)
    cwd = os.getcwd()
    LOG.info('Merging las files from {!r} using {!r} to write {!r} (symlink to name from {!r}) (and {!r})'.format(
        las_paths_fn, merge_script_fn, las_merged_symlink_fn, las_merged_fn_fn, job_done_fn))
    if os.path.lexists(las_merged_symlink_fn):
        os.unlink(las_merged_symlink_fn)
    las_merged_name_fn = io.deserialize(las_merged_fn_fn)
    script = open(merge_script_fn).read()
    las_paths = io.deserialize(las_paths_fn)
    src_dir = os.path.normpath(os.path.dirname(las_paths_fn))
    for las_path in las_paths:
        if not os.path.isabs(las_path):
            las_path = os.path.abspath(os.path.join(src_dir, las_path))
        if os.path.commonprefix([las_path, cwd]) == '/':
            src = las_path
        else:
            src = os.path.relpath(las_path, cwd)
        name = os.path.join(cwd, os.path.basename(las_path))
        LOG.info('symlink {!r} <- {!r}'.format(src, name))
        if os.path.lexists(name):
            os.unlink(name)
        os.symlink(src, name)

    script_fn = 'run_las_merge.sh'
    bash.write_script(script, script_fn, job_done_fn)
    io.syscall('bash -vex {}'.format(script_fn))
    os.symlink(las_merged_name_fn, las_merged_symlink_fn)


class HelpF(argparse.RawTextHelpFormatter, argparse.ArgumentDefaultsHelpFormatter):
    pass


def parse_args(argv):
    description = 'Merge several .las files into one, using the script generated by HPC.daligner.'
    epilog = 'The name of the merged .las file is not known to this program. It was selected by HPC.daligner. The input .las files will be symlinked into CWD so that the HPC.daligner script can find what it expects.'
    parser = argparse.ArgumentParser(
        description=description,
        epilog=epilog,
        formatter_class=HelpF,
    )
    parser.add_argument(
        '--las-paths-fn',
        help='Input. JSON list of las filenames to merge.')
    parser.add_argument(
        '--merge-script-fn',
        help='Input. Part of the output of HPC.daligner.')
    parser.add_argument(
        '--las-merged-fn-fn',
        help='Input. File which contains the file-name of the merged .las file to be generated (presumably in CWD) by the script.')
    parser.add_argument(
        '--p-id-num',
        help='Input. Just an integer, which is sort of the block number for consensus. This will go into p-id-fn.')
    parser.add_argument(
        '--las-merged-symlink-fn',
        help='Output. Symlink to the result of the script.')
    parser.add_argument(
        '--p-id-fn',
        help='Output. File containing just a single integer, the p-id-num.')
    parser.add_argument(
        '--job-done-fn',
        help='Output. Just a sentinel. (TODO: Drop.)')
    args = parser.parse_args(argv[1:])
    return args


def main(argv=sys.argv):
    args = parse_args(argv)
    logging.basicConfig(level=logging.INFO)
    run(**vars(args))


if __name__ == '__main__':  # pragma: no cover
    main()
